<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptId">
        <DeptSelect 
          style="width: 150px;" 
          v-model="queryParams.deptId" 
          placeholder="请选择部门" 
          @change="handleDeptChange"
        />
      </el-form-item>
      <el-form-item label="鱼塘" prop="pondId">
        <PondSelect 
          style="width: 120px;" 
          v-model="queryParams.pondId" 
          :dept-id="queryParams.deptId"
          placeholder="请选择鱼塘" 
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pond:fishReturn:add']"
        >新增回鱼记录</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pond:fishReturn:remove']"
        >批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch="showSearch" @queryTable="getList" @update:showSearch="showSearch = $event"></right-toolbar>
    </el-row>

    <!-- 回鱼记录表格 -->
    <el-table v-loading="loading" :data="recordList" @selection-change="handleRecordSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="用户信息" align="center" min-width="120">
        <template #default="scope">
          <div>{{ scope.row.userName }}</div>
          <div class="text-gray-500 text-sm">{{ scope.row.userPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="鱼塘" align="center" prop="pondName" />
      <el-table-column label="回鱼类型" align="center" prop="type">
        <template #default="scope">
          <span>{{ scope.row.type === 'weight' ? '按重量' : '按尾数' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回鱼数量" align="center">
        <template #default="scope">
          <span v-if="scope.row.type === 'weight'">{{ scope.row.fishWeight }}斤</span>
          <span v-else-if="scope.row.type === 'count'">{{ scope.row.fishCount }}尾</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="回鱼单价" align="center" prop="unitPrice">
        <template #default="scope">
          <span v-if="scope.row.type === 'weight'">¥{{ scope.row.unitPrice }}/斤</span>
          <span v-else-if="scope.row.type === 'count'">¥{{ scope.row.unitPrice }}/尾</span>
          <span v-else>¥{{ scope.row.unitPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回鱼金额" align="center" prop="totalAmount">
        <template #default="scope">
          <span class="text-red-500">¥{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pond:fishReturn:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pond:fishReturn:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="recordTotal > 0"
      :total="recordTotal"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改回鱼记录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="fishReturnRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单" prop="orderId" v-if="!form.orderId">
          <el-select v-model="form.orderId" placeholder="请选择订单" @change="handleOrderChange">
            <el-option
              v-for="order in orderOptions"
              :key="order.id"
              :label="`${order.orderNo} - ${order.userName}`"
              :value="order.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单信息" v-if="form.orderId && selectedOrder">
          <div class="order-info">
            <p><strong>订单编号：</strong>{{ selectedOrder.orderNo }}</p>
            <p><strong>用户：</strong>{{ selectedOrder.userName }} ({{ selectedOrder.userPhone }})</p>
            <p><strong>鱼塘：</strong>{{ selectedOrder.pondName }}</p>
            <p><strong>部门：</strong>{{ selectedOrder.deptName }}</p>
          </div>
        </el-form-item>
        <el-form-item label="回鱼类型" prop="type">
          <el-radio-group v-model="form.type" @change="handleTypeChange">
            <el-radio value="weight">按重量</el-radio>
            <el-radio value="count">按尾数</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回鱼重量" prop="fishWeight" v-if="form.type === 'weight'">
          <el-input-number
            v-model="form.fishWeight"
            :precision="2"
            :step="0.1"
            :min="0"
            placeholder="请输入回鱼重量(斤)"
            style="width: 100%"
            @change="calculateAmount"
          />
        </el-form-item>
        <el-form-item label="回鱼尾数" prop="fishCount" v-if="form.type === 'count'">
          <el-input-number
            v-model="form.fishCount"
            :precision="0"
            :step="1"
            :min="0"
            placeholder="请输入回鱼尾数"
            style="width: 100%"
            @change="calculateAmount"
          />
        </el-form-item>
        <el-form-item label="回鱼单价" prop="unitPrice">
          <el-input-number
            v-model="form.unitPrice"
            :precision="2"
            :step="0.1"
            :min="0"
            :placeholder="form.type === 'weight' ? '请输入回鱼单价(元/斤)' : '请输入回鱼单价(元/尾)'"
            style="width: 100%"
            @change="calculateAmount"
          />
        </el-form-item>
        <el-form-item label="回鱼金额" prop="totalAmount">
          <el-input-number
            v-model="form.totalAmount"
            :precision="2"
            :step="0.01"
            :min="0"
            placeholder="回鱼金额"
            style="width: 100%"
            disabled
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="FishReturn">
import { 
  listOrdersForFishReturn, 
  listFishReturn, 
  getFishReturn, 
  addFishReturn, 
  updateFishReturn, 
  delFishReturn, 
  delFishReturnBatch,
  updateFishReturnPayStatus
} from "@/api/pond/fishReturn";
import PondSelect from "@/components/PondSelect";
import DeptSelect from "@/components/DeptSelect";

const { proxy } = getCurrentInstance();
const { pond_pay_status, pond_pay_type } = proxy.useDict("pond_pay_status", "pond_pay_type");

const recordList = ref([]);
const orderOptions = ref([]);
const open = ref(false);
const paymentOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const recordIds = ref([]);
const single = ref(true);
const multiple = ref(true);
const recordTotal = ref(0);
const title = ref("");
const selectedOrder = ref(null);

const dateRange = ref([]);

const data = reactive({
  form: {},
  paymentForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    userName: null,
    userPhone: null,
    pondId: null,
    deptId: null
  },
  rules: {
    orderId: [
      { required: true, message: "订单不能为空", trigger: "change" }
    ],
    type: [
      { required: true, message: "回鱼类型不能为空", trigger: "change" }
    ],
    fishWeight: [
      { 
        validator: (rule, value, callback) => {
          if (form.value.type === 'weight' && (!value || value <= 0)) {
            callback(new Error('按重量回鱼时，回鱼重量不能为空且必须大于0'));
          } else {
            callback();
          }
        }, 
        trigger: "blur" 
      }
    ],
    fishCount: [
      { 
        validator: (rule, value, callback) => {
          if (form.value.type === 'count' && (!value || value <= 0)) {
            callback(new Error('按尾数回鱼时，回鱼尾数不能为空且必须大于0'));
          } else {
            callback();
          }
        }, 
        trigger: "blur" 
      }
    ],
    unitPrice: [
      { required: true, message: "回鱼单价不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "回鱼金额不能为空", trigger: "blur" }
    ],
  },
});

const { queryParams, form, paymentForm, rules, paymentRules } = toRefs(data);

/** 查询回鱼记录列表 */
function getList() {
  loading.value = true;
  listFishReturn(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    recordList.value = response.rows;
    recordTotal.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    orderId: null,
    type: 'weight', // 默认按重量
    fishWeight: null,
    fishCount: null,
    unitPrice: null,
    totalAmount: null,
    payStatus: 0,
    payType: null,
    remark: null
  };
  selectedOrder.value = null;
  proxy.resetForm("fishReturnRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 部门变化处理 */
function handleDeptChange(deptId) {
  // 当部门变化时，清空鱼塘选择
  queryParams.value.pondId = null;
}

/** 回鱼类型变化处理 */
function handleTypeChange(type) {
  // 清空相关字段
  if (type === 'weight') {
    form.value.fishCount = null;
  } else if (type === 'count') {
    form.value.fishWeight = null;
  }
  // 重新计算金额
  calculateAmount();
}

/** 计算回鱼金额 */
function calculateAmount() {
  const unitPrice = form.value.unitPrice || 0;
  let quantity = 0;
  
  if (form.value.type === 'weight') {
    quantity = form.value.fishWeight || 0;
  } else if (form.value.type === 'count') {
    quantity = form.value.fishCount || 0;
  }
  
  form.value.totalAmount = (unitPrice * quantity).toFixed(2);
}

/** 回鱼记录多选框选中数据 */
function handleRecordSelectionChange(selection) {
  recordIds.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 获取可回鱼的订单列表
  listOrdersForFishReturn({}).then(response => {
    orderOptions.value = response.rows;
  });
  open.value = true;
  title.value = "添加回鱼记录";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || recordIds.value;
  getFishReturn(id).then(response => {
    form.value = response.data;
    // 获取订单信息
    if (form.value.orderId) {
      listOrdersForFishReturn({ id: form.value.orderId }).then(res => {
        if (res.rows && res.rows.length > 0) {
          selectedOrder.value = res.rows[0];
        }
      });
    }
    open.value = true;
    title.value = "修改回鱼记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fishReturnRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFishReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增时需要从选中的订单中获取 pondId 和 deptId
        if (!selectedOrder.value?.pondId || !selectedOrder.value?.deptId) {
          proxy.$modal.msgError("订单信息不完整，缺少鱼塘或部门信息");
          return;
        }
        
        const submitData = {
          ...form.value,
          pondId: selectedOrder.value.pondId,
          deptId: selectedOrder.value.deptId
        };
        
        console.log('提交的数据:', submitData); // 调试信息
        
        addFishReturn(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const deleteIds = row.id || recordIds.value;
  proxy.$modal.confirm('是否确认删除回鱼记录编号为"' + deleteIds + '"的数据项？').then(function() {
    if (typeof deleteIds === 'string' && deleteIds.includes(',')) {
      return delFishReturnBatch(deleteIds);
    } else {
      return delFishReturn(deleteIds);
    }
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 支付状态更新 */
function handlePayment(row) {
  paymentForm.value = {
    id: row.id,
    payStatus: row.payStatus,
    payType: row.payType
  };
  paymentOpen.value = true;
}

/** 提交支付状态更新 */
function submitPayment() {
  proxy.$refs["paymentRef"].validate(valid => {
    if (valid) {
      updateFishReturnPayStatus(
        paymentForm.value.id, 
        paymentForm.value.payStatus, 
        paymentForm.value.payType
      ).then(response => {
        proxy.$modal.msgSuccess("更新成功");
        paymentOpen.value = false;
        getList();
      });
    }
  });
}


/** 订单选择变化 */
function handleOrderChange(orderId) {
  const order = orderOptions.value.find(item => item.id === orderId);
  if (order) {
    selectedOrder.value = order;
    console.log('选中的订单信息:', order); // 调试信息
    
    // 验证必需字段
    if (!order.pondId) {
      proxy.$modal.msgWarning("所选订单缺少鱼塘信息，请重新选择");
      return;
    }
    if (!order.deptId) {
      proxy.$modal.msgWarning("所选订单缺少部门信息，请重新选择");
      return;
    }
  }
}


onMounted(() => {
  getList();
});
</script>

<style scoped>
.order-info {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.order-info p {
  margin: 5px 0;
  font-size: 14px;
}

.text-red-500 {
  color: #f56565;
}

.text-gray-500 {
  color: #a0aec0;
}

.text-sm {
  font-size: 12px;
}
</style>